package com.xywy.me;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.xywy.R;
import com.xywy.common.BaseActivity;
import com.xywy.common.util.MD5Util;
import com.xywy.common.widget.MyProgress;
import com.xywy.common.widget.TitleBar2;
import com.xywy.fwc.net.DataCallBack;
import com.xywy.fwc.net.Request;
import com.xywy.fwc.net.StringParser;
import com.xywy.wjk.widget.TipDialog;
import com.xywy.wjk.widget.TipDialog.CancleListener;
import com.xywy.wjk.widget.TipDialog.ConfirmListener;

/**
 * 我 - 设置 - 关于云健康[去评分、功能介绍、意见反馈、检查更新]
 * @author xiaogd
 *
 */
public class SetupAboutActivity extends BaseActivity implements View.OnClickListener{
    private static final String  TAG = "SetupAboutActivity";
    private RelativeLayout rl_me_setup_about_jcgx;
    public static final String url_check_update = "http://api.yun.xywy.com/index.php/app/version/check";
    public static final String md5Key = "KHy69gsk8%#@kl$";
    public static final String tag = "wjk";
    public static final String appid = "10001";
    private String versionCode ;
    private MyProgress myProgress;
	private NotificationManager manager;
	private Notification notification;
	private PendingIntent pIntent;
	private RemoteViews notifiction_view;
	private ProgressBar notifiction_progress;
	private TextView notifiction_tv;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)  
    {
    	super.onCreate(savedInstanceState);    
        //设置为全屏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.me_setup_about);

        this.preInit();
        this.initView();
        this.loadData();
    }

    public void  onClcikSetUpAbout(View view){
        Class  cl = null;
        boolean flag =false;
         switch (view.getId()){
             case R.id.rl_me_setup_about_qpf:
                 clickPingfen();
                 break;
             case R.id.rl_me_setup_about_gnjs:
                 flag =true;
                cl = SetupAboutGnjsActivity.class;
                 break;
             case R.id.rl_me_setup_about_yjfk:

                 break;
             case R.id.rl_me_setup_about_jcgx:
            	 flag =false;
            	 checkVersionUpdate();
                 break;
             case R.id.tv_me_setup_ablut_fyxy:
                 flag =true;
                 cl = SetupAboutServiceActivity.class;
                 break;
         };
        if(flag){
            Intent  intent = new Intent(SetupAboutActivity.this,cl);
            startActivity(intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    public void preInit() {
    	myProgress = new MyProgress(this, 15000);
    }

    @Override
    public void loadData() {

    }

    @Override
    public void initView() {
        //title
        TitleBar2 titleBar = (TitleBar2)findViewById(R.id.me_setup_about_title_bar);
        titleBar.onClickBack(this);
            TextView tvTitle= titleBar.getTitle();
            TextView tvBack= titleBar.getTvBack();
            titleBar.getGo().setVisibility(View.INVISIBLE);
            tvTitle.setText(getString(R.string.me_setup_about));
            tvBack.setText(getString(R.string.me_setup_title ));
            rl_me_setup_about_jcgx = (RelativeLayout) findViewById(R.id.rl_me_setup_about_jcgx);
      
            manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            notification =new Notification();
           Intent intent=new Intent(SetupAboutActivity.this,SetupAboutActivity.class);
            pIntent=PendingIntent.getService(SetupAboutActivity.this, 0, intent, 0);
            notifiction_view = new RemoteViews(getPackageName(),R.layout.download_notifiction_progress);
//            notifiction_progress = (ProgressBar) notifiction_view.findViewById(R.id.progress_bar);
//            notifiction_tv = (TextView) notifiction_view.findViewById(R.id.tv_notification);
    }


    @Override
    public void onClick(View view) {

    }

    private  void  clickPingfen(){
        Uri uri = Uri.parse("market://details?id=" + getPackageName());
        Intent intent = new Intent(Intent.ACTION_VIEW,uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
    
    private String versonUrl;
    
    private void checkVersionUpdate(){
    	myProgress.start();
    	HashMap<Object, Object> params = new HashMap<Object, Object>();
    	try {
			params.put("sign", MD5Util.md5(md5Key+tag));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	params.put("tag", tag);
    	params.put("appid", appid);
    	try {
    		params.put("versionCode", getVersionCode());
    		System.out.println(getVersionCode());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
    	Request.postData(new StringParser(), new DataCallBack<String>() {

			@Override
			public void dataCall(final String t) {
				// TODO Auto-generated method stub
				runOnUiThread(new Runnable() {
					public void run() {
						myProgress.stop();
						if(t==null){
							Toast.makeText(context, "网络异常,检查版本失败", Toast.LENGTH_SHORT).show();
						}else {
							System.out.println("检查版本返回的"+t);
							try {
								JSONObject json = new JSONObject(t);
								versonUrl = json.optString("url");
								if(versonUrl != null && !"".equals(versonUrl)){
									showDownloadDialog();
//									System.out.println("更新地址 "+versonUrl);
//									Toast.makeText(SetupAboutActivity.this, "您现在已经是最新版本了", Toast.LENGTH_SHORT).show();
								}else {
									Toast.makeText(SetupAboutActivity.this, "您现在已经是最新版本了", Toast.LENGTH_SHORT).show();
								}
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				});
			}
		}, url_check_update, params);
    }
    
    private void showDownloadDialog(){
    	final TipDialog dialog = new TipDialog(this, TipDialog.VIEW_DIALOG);
		dialog.setTitleAndContent("更新", "下载最新安装包");
		dialog.setConfirmCallback(new ConfirmListener() {

			@Override
			public void confirm() {
				dialog.dismiss();
				Toast.makeText(SetupAboutActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
				downLoadPackage();
			}

		});
		dialog.setCancleCallback(new CancleListener() {

			@Override
			public void cancle() {
				dialog.dismiss();
			}
		});
		dialog.show();
    }
    
    /**
     * 下载apk
     */
    private void downLoadPackage(){
    	new Thread(){
    		@Override
    		public void run() {
    			try {
    				URL url = new URL(versonUrl);
    				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				    conn.setConnectTimeout(15000);
				    conn.setReadTimeout(30000);
				    int code = conn.getResponseCode();
				    if(code == 200){
				    	InputStream ins = conn.getInputStream();
				    	byte[] buf = new byte[1024];
				    	String fileStr = Environment.getExternalStorageDirectory()+"/"+"云健康.apk";
						File file = new File(fileStr);
						if(file.exists()){
							
						}else {
							File parentF = file.getParentFile();
							parentF.mkdir();
							file.createNewFile();
						}
				    	FileOutputStream fos = new FileOutputStream(new File(fileStr));
				    	max = ins.available();
				    	while (ins.available()>=1024 && ins.read(buf)!= -1) {
							fos.write(buf);
							currentProgress = max - ins.available();
							apkDownloadHandler.sendEmptyMessage(down);
						}
				    	int temp ;
				    	if(ins.available() > 0 && (temp=ins.read())!= -1){
				    		fos.write(temp);
				    	}
				    	apkDownloadHandler.sendEmptyMessage(finish);
				    	fos.flush();
				    	fos.close();
				    	ins.close();
				    }
    			} catch (Exception e) {
					e.printStackTrace();
				}
    			
    		}
    	}.start();
    }
    int max;
    int currentProgress;
    static final int down = 0;
    static final int finish = 1;
    
    private Handler apkDownloadHandler = new Handler(){
    	public void handleMessage(Message msg) {
    		switch (msg.what) {
			case down:
				 notification.contentView=notifiction_view;
	    		  notification.contentView.setProgressBar(R.id.progress_bar, max, currentProgress, false);
	              notification.contentIntent=pIntent;
	              manager.notify(0, notification);
				break;
			case finish:
				notification.contentView.setTextViewText(R.id.tv_notification, "下载完成");
				break;

			default:
				break;
			}
    	};
    };
    
    private int getVersionCode() throws Exception
    {
            // 获取packagemanager的实例
            PackageManager packageManager = getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),0);
            int version = packInfo.versionCode;
            return version;
    }
    
}



